<template>
  <div class="app-container">
    <div class="search-bar">
      <div class="search-input-wrapper">
        <i class="fas fa-search search-icon"></i>
        <input
          type="text"
          placeholder="搜索关键字"
          v-model="searchKeyword"
          @input="fetchOrders"
        />
      </div>
      <div class="button-group">
        <button @click="exportExcel">导出Excel</button>
        <button @click="backToPreviousPage">返回</button>
      </div>
    </div>

    <div class="tab-container">
      <button
        v-for="tab in tabs"
        :key="tab.value"
        :class="{ 
          'active': currentTab === tab.value,
          'tab-button': true
        }"
        @click="switchTab(tab.value)"
      >
        {{ tab.label }}
      </button>
    </div>

    <div v-if="!isLoading" class="table-container">
      <table>
        <thead>
          <tr>
            <th>序号</th>
            <th>标准名称</th>
            <th>项目名称</th>
            <th>设备名称</th>
            <th>解决方案</th>
            <th>发起人</th>
            <th>状态</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="(item, index) in paginatedOrders" :key="item.odId">
            <td>{{ (currentPage - 1) * itemsPerPage + index + 1 }}</td>
            <td>{{ item.staName }}</td>
            <td>{{ item.pjName }}</td>
            <td>{{ item.eName }}</td>
            <td>{{ item.soName }}</td>
            <td>{{ item.uRealName }}</td>
            <td>
              <span class="status-tag" :class="item.oStatus === '计划采购' ? 'status-pending' : 'status-completed'">
                {{ item.oStatus }}
              </span>
            </td>
            <td class="operation-cell">
              <button @click="completeOrder(item)" v-if="item.oStatus === '计划采购'" class="complete-button">
                购置完成
              </button>
              <button @click="deleteOrder(item)" v-else class="delete-button">
                删除
              </button>
            </td>
          </tr>
        </tbody>
      </table>
      <div class="pagination-container">
        <Pagination
          :current-page="currentPage"
          :total-items="filteredOrders.length"
          :items-per-page="itemsPerPage"
          @page-changed="handleCurrentChange"
          @items-per-page-changed="handleSizeChange"
        />
      </div>
    </div>

    <div v-else class="loading-container">
      加载中...
    </div>
  </div>
</template>



<script>
import axios from 'axios'
import Pagination from "@/components/Pagination.vue"

export default {
  components: {
    Pagination
  },
  data() {
    return {
      searchKeyword: '',
      currentTab: 'plan',
      orders: [],
      currentPage: 1,
      itemsPerPage: 10,
      isLoading: false,
      tabs: [
        { label: '计划采购', value: 'plan' },
        { label: '已完成', value: 'completed' }
      ]
    }
  },

  computed: {
    paginatedOrders() {
      const start = (this.currentPage - 1) * this.itemsPerPage
      const end = start + this.itemsPerPage
      return this.filteredOrders.slice(start, end)
    },

    filteredOrders() {
      if (!this.searchKeyword) return this.orders

      const keyword = this.searchKeyword.toLowerCase()
      return this.orders.filter(order => 
        order.staName?.toLowerCase().includes(keyword) ||
        order.pjName?.toLowerCase().includes(keyword) ||
        order.eName?.toLowerCase().includes(keyword) ||
        order.soName?.toLowerCase().includes(keyword)||
        order.uRealName?.toLowerCase().includes(keyword)
      )
    }
  },

  methods: {
    async fetchOrders() {
      this.isLoading = true
      try {
        const response = await axios.get(
          this.currentTab === 'plan' 
            ? 'http://localhost:8081/orders/pending'
            : 'http://localhost:8081/orders/completed'
        )
        this.orders = response.data
      } catch (error) {
        console.error('获取订单失败:', error)
        this.$message.error('获取数据失败')
      } finally {
        this.isLoading = false
      }
    },

    async switchTab(tabValue) {
      if (this.currentTab === tabValue) return
      this.currentTab = tabValue
      this.currentPage = 1
      await this.fetchOrders()
    },

    async completeOrder(item) {
      try {
        await axios.put(`http://localhost:8081/orders/${item.odId}/complete`)
        this.$message.success('订单已完成')
        await this.fetchOrders()
      } catch (error) {
        console.error('完成订单失败:', error)
        this.$message.error('操作失败')
      }
    },

    async deleteOrder(item) {
      try {
        await this.$confirm('确认删除该订单?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        await axios.delete(`http://localhost:8081/orders/${item.odId}`)
        this.$message.success('删除成功')
        await this.fetchOrders()
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除订单失败:', error)
          this.$message.error('删除失败')
        }
      }
    },

    async exportExcel() {
      try {
        const response = await axios.get(
          this.currentTab === 'plan'
            ? 'http://localhost:8081/orders/exportPending'
            : 'http://localhost:8081/orders/exportCompleted',
          { responseType: 'blob' }
        )
        
        const blob = new Blob([response.data], {
          type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        })
        const link = document.createElement('a')
        link.href = window.URL.createObjectURL(blob)
        link.download = `订单列表_${this.currentTab === 'plan' ? '计划采购' : '已完成'}.xlsx`
        link.click()
      } catch (error) {
        console.error('导出失败:', error)
        this.$message.error('导出失败')
      }
    },

    backToPreviousPage() {
      this.$router.go(-1)
    },

    handleCurrentChange(val) {
      this.currentPage = val
    },

    handleSizeChange(val) {
      this.itemsPerPage = val
      this.currentPage = 1
    }
  },

  created() {
    this.fetchOrders()
  }
}
</script>
<style scoped>
.app-container {
  padding: 20px;
}

.search-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.search-input-wrapper {
  position: relative;
  width: 300px;
}

.search-icon {
  position: absolute;
  left: 10px;
  top: 50%;
  transform: translateY(-50%);
  color: #999;
}

.search-bar input {
  width: 100%;
  padding: 8px 12px 8px 35px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
}

.button-group {
  display: flex;
  gap: 8px;
}

.button-group button {
  padding: 8px 16px;
  border: none;
  background-color: #409EFF;
  color: white;
  border-radius: 4px;
  cursor: pointer;
}

.tab-container {
  display: flex;
  margin-bottom: 15px;
}

.tab-container button {
  flex: 1;
  padding: 10px;
  border: none;
  background-color: #f1f1f1;
  color: #333;
  cursor: pointer;
  border-radius: 4px 4px 0 0;
}

.tab-container button.active {
  background-color: #409EFF;
  color: white;
}

.table-container {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  width: 85%;
  margin: 0 auto;
}

table {
  width: 100%;
  border-collapse: collapse;
}

th, td {
  padding: 12px;
  text-align: center;
  border-bottom: 1px solid #ebeef5;
  vertical-align: middle;
}

.operation-cell {
  text-align: center;
  white-space: nowrap;
}

.complete-button,
.delete-button {
  padding: 6px 12px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
  margin: 0 4px;
}

.complete-button {
  background-color: #409EFF;
  color: white;
}

.delete-button {
  background-color: #f56c6c;
  color: white;
}

.complete-button:hover {
  background-color: #66b1ff;
}

.delete-button:hover {
  background-color: #ff7875;
}

/* 状态标签样式 */
.status-tag {
  display: inline-block;
  padding: 6px 12px;
  border-radius: 15px;
  font-size: 13px;
  font-weight: 500;
}

.status-pending {
  background-color: #fff2f0;
  color: #ff4d4f;
  border: 1px solid #ffccc7;
}

.status-completed {
  background-color: #f6ffed;
  color: #52c41a;
  border: 1px solid #b7eb8f;
}

/* 响应式布局 */
@media screen and (max-width: 768px) {
  .table-container {
    width: 95%;
    padding: 10px;
  }

  th, td {
    padding: 8px;
    font-size: 14px;
  }
}

.loading-container {
  text-align: center;
  padding: 20px;
  color: #909399;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

:deep(.pagination) {
  display: flex;
  align-items: center;
  gap: 10px;
}

:deep(.pagination button) {
  padding: 8px 12px;
  border: none;
  background-color: #409EFF !important;
  color: white !important;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
}

:deep(.pagination button:disabled) {
  background-color: #c0c4cc !important;
  cursor: not-allowed;
}

:deep(.pagination button:hover:not(:disabled)) {
  background-color: #66b1ff !important;
}

:deep(.pagination .page-input) {
  width: 60px;
  padding: 6px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  text-align: center;
}

:deep(.pagination select) {
  padding: 6px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  cursor: pointer;
}
</style>
